<script setup>
import { computed } from 'vue';
import { Icon } from '@iconify/vue';
import { ref } from 'vue';

const props = defineProps({
  rows: {
    type: Number,
    default: 5
  },
  cols: {
    type: Number,
    default: 12
  },
  list: {
    type: Array,
    default: () => []
  },
  page: {
    type: Number,
    default: 1
  }
});

const emits = defineEmits(['change']);

const showLength = props.cols * props.rows;
const showList = computed(() => {
  return props.list.slice((props.page - 1) * showLength, props.page * showLength);
});

const activeIndex = ref(0);

const handleClick = index => {
  activeIndex.value = index;
  emits('change', index + showLength * (props.page - 1));
};

const changePage = () => {
  emits('change', activeIndex.value + showLength * (props.page - 1));
};

defineExpose({
  changePage
});
</script>
<template>
  <div
    class="w-full grid-container"
    :style="{
      gridTemplateColumns: `repeat(${cols}, 1fr)` /* 创建16列 */,
      gridTemplateRows: `repeat(${rows}, 1fr)`
    }"
  >
    <div v-for="rowIndex in rows" :key="'row-' + rowIndex" class="grid-row">
      <div
        v-for="colIndex in cols"
        :key="'col-' + colIndex"
        class="grid-item"
        :class="activeIndex === (rowIndex - 1) * cols + (colIndex - 1) ? 'bg-blue-100' : ''"
        @click="handleClick((rowIndex - 1) * cols + (colIndex - 1))"
      >
        <Icon :icon="showList[(rowIndex - 1) * cols + (colIndex - 1)]" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.grid-container {
  display: grid;
  gap: 1px; /* 单元格之间的间隙 */
  border: 1px solid #ccc; /* 整个网格的边框 */
}

.grid-item {
  border: 1px solid #ddd; /* 单元格的边框 */
  display: flex; /* 使用 flex 布局 */
  justify-content: center; /* 居中 */
  align-items: center; /* 居中 */
  font-size: 14px; /* 字体大小 */
  aspect-ratio: 1/1;
}

.grid-row {
  display: contents; /* 允许子项在网格中直接对齐 */
}
</style>
